using Magiq.Behaviors;
using Magiq.Update;

namespace Magiq.Databases.Update
{
    public class DatabaseUpdateStrategy<T> : BehaviorHandler<IDatabaseUpdateBehavior<T>>, IUpdateStrategy,
                                             IDatabaseBasedExecution where T : class
    {
        public DatabaseUpdateStrategy(IDatabaseAdapter databaseAdapter, IUpdate<T> update)
            : base(update.Behavior)
        {
            DatabaseAdapter = databaseAdapter;
            this.update = update;
            Default<DatabaseUpdateBehavior<T>>();
        }

        public IDatabaseAdapter DatabaseAdapter { get; private set; }

        private readonly IUpdate<T> update;

        public int Execute()
        {
            Call(x => x.Initialize(DatabaseAdapter, update));
            var updates = Call(x => x.BuildDatabaseUpdates());
            var result = 0;
            foreach (var update in updates)
            {
                var command = Call(x => x.BuildCommand(update));
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }
    }
}